package com.zyf.wjy.service;

import com.zyf.wjy.dao.*;
import com.zyf.wjy.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 统计分析服务类
 */
@Service
public class StatisticsService {
    
    @Autowired
    private FarmingRecordDao farmingRecordDao;
    
    @Autowired
    private ProductDao productDao;
    
    @Autowired
    private SalesRecordDao salesRecordDao;
    
    @Autowired
    private PlantingPlanDao plantingPlanDao;
    
    @Autowired
    private FieldDao fieldDao;
    
    /**
     * 统计生产成本（按农事类型）
     */
    public Map<String, Double> getProductionCostByType() {
        List<FarmingRecord> records = farmingRecordDao.findAll();
        return records.stream()
            .filter(r -> r.getCost() != null)
            .collect(Collectors.groupingBy(
                FarmingRecord::getFarmingType,
                Collectors.summingDouble(FarmingRecord::getCost)
            ));
    }
    
    /**
     * 统计销售额（按月份）
     */
    public Map<String, Double> getSalesByMonth() {
        List<SalesRecord> records = salesRecordDao.findAll();
        return records.stream()
            .filter(r -> r.getSalesDate() != null && r.getTotalAmount() != null)
            .collect(Collectors.groupingBy(
                r -> r.getSalesDate().getYear() + "-" + String.format("%02d", r.getSalesDate().getMonthValue()),
                Collectors.summingDouble(SalesRecord::getTotalAmount)
            ));
    }
    
    /**
     * 统计产量（按作物）
     */
    public Map<String, Double> getYieldByCrop() {
        List<Product> products = productDao.findAll();
        return products.stream()
            .filter(p -> p.getQuantity() != null)
            .collect(Collectors.groupingBy(
                Product::getProductName,
                Collectors.summingDouble(Product::getQuantity)
            ));
    }
    
    /**
     * 统计销量（按产品）
     */
    public Map<String, Double> getSalesVolumeByProduct() {
        List<SalesRecord> records = salesRecordDao.findAll();
        return records.stream()
            .filter(r -> r.getQuantity() != null)
            .collect(Collectors.groupingBy(
                SalesRecord::getProductName,
                Collectors.summingDouble(SalesRecord::getQuantity)
            ));
    }
    
    /**
     * 获取首页统计数据
     */
    public Map<String, Object> getDashboardStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 地块统计
        List<Field> fields = fieldDao.findAll();
        stats.put("totalFields", fields.size());
        stats.put("usedFields", fields.stream().filter(f -> f.getStatus() == 1).count());
        
        // 种植计划统计
        List<PlantingPlan> plans = plantingPlanDao.findAll();
        stats.put("totalPlans", plans.size());
        stats.put("executingPlans", plans.stream().filter(p -> "executing".equals(p.getStatus())).count());
        
        // 产品库存统计
        List<Product> products = productDao.findAll();
        stats.put("totalProducts", products.size());
        stats.put("totalStock", products.stream().mapToDouble(p -> p.getQuantity() != null ? p.getQuantity() : 0).sum());
        
        // 销售统计（本月）
        LocalDate now = LocalDate.now();
        List<SalesRecord> salesRecords = salesRecordDao.findAll();
        double monthSales = salesRecords.stream()
            .filter(r -> r.getSalesDate() != null 
                && r.getSalesDate().getYear() == now.getYear() 
                && r.getSalesDate().getMonthValue() == now.getMonthValue())
            .mapToDouble(r -> r.getTotalAmount() != null ? r.getTotalAmount() : 0)
            .sum();
        stats.put("monthSales", monthSales);
        
        // 成本统计（本月）
        List<FarmingRecord> farmingRecords = farmingRecordDao.findAll();
        double monthCost = farmingRecords.stream()
            .filter(r -> r.getFarmingDate() != null 
                && r.getFarmingDate().getYear() == now.getYear() 
                && r.getFarmingDate().getMonthValue() == now.getMonthValue())
            .mapToDouble(r -> r.getCost() != null ? r.getCost() : 0)
            .sum();
        stats.put("monthCost", monthCost);
        
        return stats;
    }
}

